// pages/exam/exam.js
const app = getApp();
Page({
  data: {
    isNull: false,
    current: 0,
    viewMode: false,
    showAnswer: false,
    screenHeight: app.globalData.safearea.height,
    windowHeight: app.globalData.safearea.windowHeight,
    progressWidth: 0,
    show: false
  },
  onClose() {
    this.setData({ show: false });
  },
  onHide() {
    this.onClose();
  },
  onShow() {
    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(()=> {
        wx.switchTab({
          url: '/pages/index/index',
        });
      }, 1500);
      return;
    }
    // 加载app.globalData.exam1Params
    if (!('vip' in app.globalData.userinfo) || JSON.stringify(app.globalData.userinfo.vip) === '{}') {
      console.log('当前', app.globalData.userinfo)
      wx.showModal({
        title: '开通会员',
        content: '解锁本专业全部题目',
        confirmText: '确认开通',
        cancelText: '返回首页',
        complete: (res) => {
          if (res.cancel) {
            wx.switchTab({
              url: '/pages/index/index'
            });
          }
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/buy/buy'
            });
          }
        }
      })
    }
    // if (app.globalData.exam1ParamsNeedLoad) {
      this.setData({
        examList: [],
        current: 0,
        isNull: false,
        progressWidth: 0
      });
      const that = this;
      wx.showLoading({
        title: '加载题目'
      });
      that.loadData();
      // 开启一个计时器
      this.time = 0;
      this.timeIntval = setInterval(() => {
        this.time++;
      }, 1000);
  },
  loadData() {
    const that = this;
    app.request('/api/question/list', {paper: 1, category_id: app.globalData.category.id}).then(res => {
      const data = res.data.data;
      for(let i = 0;i < data.list.length;i++) {
        let options = JSON.parse(data.list[i].option_json);
        let options_arr = [];
        for(let option in options) {
          options_arr.push({name: option, value: options[option]});
        }
        // if (app.globalData.exam1ViewMode) {
        //   data[i].show_answer = true;
        //   data[i].selected = data[i].answer_tags.split(',');
        // } else {
        data.list[i].show_answer = false;
        data.list[i].selected = [];
        // }
        data.list[i].option_json = options_arr;
      }
      if (data.list.length > 0) {
        that.setData({
          progressWidth: 1 / data.length * 100,
          examList: data.list,
          typeList: data.type,
          total: data.total
        });
        setTimeout(() => {
          that.setData({
            show: true
          });
          wx.hideLoading();
        }, 1000)
      } else {
        that.setData({
          isNull: true
        });
      }
      
    }).catch(err => {
      wx.hideLoading();
      console.error(err);
    })
  },
  selectOption(e) {
    const examList = this.data.examList;
    const item = examList[e.target.dataset.itemindex];
    const option = item.option_json[e.target.dataset.optionindex];
    let selected = item.selected;
    if (item.show_answer) return;
    if (item.question_type_id == 2) {
      // 多选
      console.log('option', option)
      console.log('selected', selected)
      let sindex = selected.indexOf(option.name)
      if (sindex > -1) {
        selected.splice(sindex, 1)
      } else {
        selected.push(option.name)
      }
      selected = selected.sort();
    } else {
      // 判断题与单选题
      selected = [option.name]
    }
    this.setData({
      [`examList[${e.target.dataset.itemindex}].selected`]: selected
    });
  },
  finshJob() {
    // 统计数据
    wx.showLoading({
      title: '正在交卷'
    });
    const examList = this.data.examList;
    let count = 0;
    for (const exam of examList) {
      if (exam.selected.length > 0) {
        count++; // 已答
      }
    }
    let title = '还有未答题目，确认交卷吗';
    if (count === examList.length) {
      title = '确认交卷吗';
    }
    const that = this;
    wx.showModal({
      title: title,
      cancelText: '取消',
      confirmText: '确认交卷',
      complete: (res) => {
        if (res.cancel) {
          console.log('取消交卷');
          wx.hideLoading();
        }
        if (res.confirm) {
          for (const exam of examList) {
            if (exam.selected.length > 0) {
              this.saveExam(exam.id, exam.selected.join(',')); // 检测未保存的题目
            }
          }
          wx.hideLoading();
          console.log('执行交卷');
          that.saveAnswer();
        }
      }
    });
  },
  saveAnswer() {
    // 将数据传到result
    const that = this;
    wx.navigateTo({
      url: './result/result',
      success: function(res) {
        res.eventChannel.emit('examList', { examList: that.data.examList }) // 从头开始做题
        // 要把当前题目置为看题模式
        let examList = that.data.examList;
        let saveRes = [];
        let score = 0;
        for (let i = 0;i < examList.length;i++) {
          examList[i].show_answer = true;
          if (examList[i].selected.join(',') === examList[i].answer_tags) {
            score++;
          }
          saveRes.push({question: examList[i].id, answer: examList[i].selected.join(',')});
        }
        // if (app.globalData.exam1Title === '模拟成绩') {
          clearInterval(that.timeIntval);
          let min = parseInt(that.time / 60);
          let yu = that.time % 60;
          if (yu > 0) min++;
          console.log('用时：', min);
          console.log('得分：', score);
          console.log('saveRes：', saveRes);
          app.request('/api/question/examSave', {category_id: app.globalData.category.id,answer: JSON.stringify(saveRes), score: score, true_num: score, false_num: (saveRes.length-score), take_time: min}, 'POST').then(res => {
            console.log(res.data);
          }).catch(err => {
            console.error(err);
          });
        // }
        that.setData({
          examList: examList
        })
      }
    })
  },
  onSwiperChange (e) {
    if (e.detail.source === 'touch') {
      this.setData({
        current: e.detail.current,
        progressWidth: ((e.detail.current + 1) / this.data.examList.length) * 100 // 计算进度条宽度百分比
      });
    }
  },
  doCollect() {
    const item = this.data.examList[this.data.current];
    const that = this;
    let star = item.star ? 0 : 1;
    that.setData({
      [`examList[${that.data.current}].star`]: star
    });
    app.request('/api/question/userStar', {question_id: item.id, star: star}, 'POST').then(res => {
    }).catch(err => {
      console.error(err);
    });
  },
  // showAnswer: function (e) {
  //   // console.log('选择的答案:', e.target.dataset.index);
  //   const examList = this.data.examList;
  //   if (examList[e.target.dataset.index].selected.length <= 0) return;
  //   this.setData({
  //     [`examList[${e.target.dataset.index}].show_answer`]: true
  //   });
  //   // 保存答题记录
  //   // this.saveExam(examList[e.target.dataset.index].id, examList[e.target.dataset.index].selected.join(','));
  // },
  saveExam(id, answer) {
    app.request('/api/question/userAnswer', {question_id: id, answer: answer}, 'POST').then(res => {
    }).catch(err => {
      console.error(err);
    })
  },
  prevQuestion: function () {
    if (this.data.current === 0) return;
    let i = this.data.current - 1;
    console.log('i', i);
    this.setData({
      current: i,
      progressWidth: ((i+1) / this.data.examList.length) * 100
    });
  },
  nextQuestion: function () {
    if ((this.data.current+1) >= this.data.examList.length) return;
    let i = this.data.current + 1;
    console.log('i', i);
    this.setData({
      current: i,
      progressWidth: ((i+1) / this.data.examList.length) * 100
    });
  }
});
